package com.hbnu.tonghengchang;

import java.io.*;
import java.net.*;

public class Picture {
    private static final int PORT = 8889;

    // 图片服务器
    public static void startServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("图片服务器启动...");

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> handleImageUpload(socket)).start();
        }
    }

    private static void handleImageUpload(Socket socket) {
        try (DataInputStream dis = new DataInputStream(socket.getInputStream())) {
            String imageName = dis.readUTF();
            long fileSize = dis.readLong();

            try (FileOutputStream fos = new FileOutputStream("uploaded_" + imageName)) {
                byte[] buffer = new byte[8192];
                int read;
                long remaining = fileSize;

                while (remaining > 0 && (read = dis.read(buffer, 0, (int)Math.min(buffer.length, remaining))) != -1) {
                    fos.write(buffer, 0, read);
                    remaining -= read;
                }
            }
            System.out.println("图片上传完成: " + imageName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 图片客户端
    public static void uploadImage(String imagePath) throws IOException {
        Socket socket = new Socket("localhost", PORT);
        File imageFile = new File(imagePath);

        try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
             FileInputStream fis = new FileInputStream(imageFile)) {

            dos.writeUTF(imageFile.getName());
            dos.writeLong(imageFile.length());

            byte[] buffer = new byte[8192];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, read);
            }
            dos.flush();
        }
        System.out.println("图片发送完成: " + imageFile.getName());
    }

    public static void main(String[] args) throws IOException {
        if (args.length > 0 && "server".equals(args[0])) {
            startServer();
        } else {
            uploadImage("test.jpg"); // 测试图片
        }
    }
}
